// 获取全局 app 实例
const app = getApp();
Page({
  data: {

  },
  onLoad() {},
  pageTo(e) {
    // console.log(e.currentTarget.dataset.link)
    my.navigateTo({
      url: e.currentTarget.dataset.link
    })
  },

  async uploadFile() {
    const c1 = my.cloud.createCloudContext({
      env: 'env-00jxgeypg2iy', // 云环境 id
    });


    var token = "";
    const AK = "itt6KNwI030cUSX1KtdFqFms"
    const SK = "HSQuraUDejnuAynozGaP9cTzh12LQVlV"
    my.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
      method: 'POST',
      headers: {
        'content-type': 'application/json', //默认值
      },
      dataType: 'json',
      success: function (res) {
        // my.alert({
        //   content: 'success'
        // });
      },
      fail: function (error) {
        console.error('fail: ', JSON.stringify(error));
      },
      complete: function (res) {
        console.log("res", res);
        token = res.data.access_token;
        console.log("res", token);
        my.hideLoading();
        // my.alert({
        //   content: 'complete'
        // });
      },
    });

    my.chooseImage({
      success: res => {
        const fs = my.getFileSystemManager();
        fs.readFile({
          filePath: `${res.apFilePaths[0]}`,
          // readFile 不传入 encodding 参数，则以 ArrayBuffer 方式读取
          success: ({
            data
          }) => {
            const base64 = my.arrayBufferToBase64(data);


            this.perse(base64, token);
            my.showLoading({
              content: '解析中...解析耗时较长，请耐心等待',
              success: function (res) {
                console.log(res);
                setTimeout(() => {
                  my.hideLoading();

                }, 5000);
              },
              fail: function (err) {
                console.log(err);
              }
            });
          },
        });
      }
    });



    // 选择图片
    // my.chooseImage({
    //   success: (imgRes) => {
    //     // 云环境初始化 
    //     c1.init({
    //       success: () => {
    //         // 调用云存储上传接口
    //         c1.uploadFile({
    //           cloudPath: imgRes.tempFilePaths[0],
    //           filePath: imgRes.tempFilePaths[0],
    //           success: (res) => {
    //             console.log("===", res.fileID)
    //             // 获取云文件临时链接
    //             c1.getTempFileURL({
    //               fileList: [{
    //                 fileID: res.fileID,
    //                 maxAge: 3600
    //               }],
    //               success: (res) => {
    //                 console.log("==", res.fileList[0].tempFileURL);

    //                 this.callOcr(res.fileList[0].tempFileURL),

    //                   my.showLoading({
    //                     content: '加载中...',
    //                     success: function (res) {
    //                       console.log(res);
    //                       setTimeout(() => {
    //                         my.hideLoading();

    //                       }, 4000);
    //                     },
    //                     fail: function (err) {
    //                       console.log(err);
    //                     }
    //                   });


    //               }
    //             });

    //           }
    //         });
    //       }
    //     });
    //   }
    // });
  },


  // perse: function (e) {
  //   e = this.data;
  //   console.log("base:", e);
  //   let arr = [];
  //   words = e.data.words_result;

  //   for (let result1 of words) {
  //     //console.log("result1", result1);
  //     arr.push(result1.words);
  //     // console.log("result1", result1.words);
  //     if (result1.words.toString().includes("%")) {
  //       let str = arr[arr.length - 3];
  //       let fundName = "";
  //       let fundAmt = "";
  //       if (str.includes(".")) {
  //         fundName = arr[arr.length - 5];
  //         fundAmt = arr[arr.length - 4].replace(",", "");
  //       } else if (str === "定投") {
  //         fundName = arr[arr.length - 6];
  //         fundAmt = arr[arr.length - 5].replace(",", "");
  //       } else {
  //         fundName = arr[arr.length - 6] + arr[arr.length - 3];
  //         fundAmt = arr[arr.length - 5].replace(",", "");
  //       }
  //       console.log("rundName", fundName);
  //       console.log("fundAmt", fundAmt);

  //       //this.getFundCode(fundName);

  //       c1.callFunction({
  //         name: "addFundInfo",
  //         data: {
  //           action: "addFundInfo",
  //           fundName: fundName,
  //           fundAmt: fundAmt
  //         }
  //       });



  //     }



  //   }



  // },

  callBaiduOcr(e) {
    console.log("baiduocr:", e);


  },
  async getFundCode(e) {
    const c1 = my.cloud.createCloudContext({
      env: 'env-00jxgeypg2iy', // 云环境 id
    });
    var res = await c1.callFunction({
      name: "getFundListInfo",
      data: {
        action: "getFundInfos",
        fundName: e
      }
    });
    // console.log("resres", res);

    console.log("resres", res.result[0]);
    return res.result[0];

  },
  async callOcr(e) {

    let ropenides = my.getStorageSync({
      key: 'openid'
    });

    console.log("eeeee", ropenides.data);
    var context = app.context;
    await context.init()
    const res = context.callContainer({
      path: '/alipaycloud/baidu/baseocr',
      method: 'POST',
      data: {
        "openId": ropenides.data,
        "filePath": e
      },
      header: {
        "X-Alipay-Service": "yongserver", //换成你自己的环境内的服务名
        "Content-Type": "application/json" // 不加这一行，其实就不需要服务端返回的数据限制为json了。啥都不加，其实默认就是 text，如果加了 json，jsapi就可以帮助反序列化json，
      }
    }).then((res) => {
      console.log("add then respose", res);
      let rees = my.setStorageSync({
        key: 'fundInfoList',
        data: res.resultData.data
      });

      my.reLaunch({
        url: "../index/index?data=" + res.resultData.data // url详解请见【路由使用须知】
      });
      console.log(rees);
      if (rees.success) {
        console.log("执行成功");

      }


    })


  },
  async perse(base64, token) {
    var currentDate = new Date();
    // 使用getTime()方法获取时间戳（毫秒）  
    var timestamp = currentDate.getTime();
    var context = app.context;
    // 打印时间戳  
    console.log(timestamp);
    const c1 = my.cloud.createCloudContext({
      env: 'env-00jxgeypg2iy', // 云环境 id
    });


    let words = [];
    const res = "";
    var ocrResult = "";
    // 转为 base64 后使用 my.request 将数据传给后端
    await my.request({
      url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=' + token,
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      },
      data: {
        'image': base64,
        'detect_direction': 'false',
        'paragraph': 'false',
        'probability': 'false'

      },
      dataType: 'json',
      success: function (res) {

      },
      fail: function (error) {
        console.error('fail: ', JSON.stringify(error));
      },
      complete: function (res) {
        ocrResult = res;


      },

    });

    let arr = [];






    words = ocrResult.data.words_result;
    for (let result1 of words) {
      //console.log("result1", result1);
      arr.push(result1.words);
      // console.log("result1", result1.words);
      if (result1.words.toString().includes("%")) {
        let str = arr[arr.length - 3];
        let fundName = "";
        let fundAmt = "";
        let todayAmt = "";
        if (str.includes(".")) {
          fundName = arr[arr.length - 5];
          fundAmt = arr[arr.length - 4].replace(",", "");
          todayAmt = arr[arr.length - 2].replace(",", "");
        } else if (str === "定投") {
          fundName = arr[arr.length - 6];
          fundAmt = arr[arr.length - 5].replace(",", "");
          todayAmt = arr[arr.length - 2].replace(",", "");
        } else {
          fundName = arr[arr.length - 6] + arr[arr.length - 3];
          fundAmt = arr[arr.length - 5].replace(",", "");
          todayAmt = arr[arr.length - 2].replace(",", "");
        }
        console.log("rundName", fundName);
        console.log("fundAmt", fundAmt);

        console.log("todayAmt", todayAmt);

        var fundCodeInfo = await c1.callFunction({
          name: "getFundListInfo",
          data: {
            action: "getFundInfos",
            fundName: fundName
          }
        });
        // console.log("resres", res);



        let ropenides = my.getStorageSync({
          key: 'openid'
        });

        console.log("eeeee", ropenides.data);
        var list = [];
        var fundCode = "";
        if (fundCodeInfo.result[0] != null) {
          fundCode = fundCodeInfo.result[0].code;
          console.log("fund", fundCode);

          var fund = {

            fundName: fundName,
            fundCode: fundCode,
            fundAmt: fundAmt,
            todayAmt: todayAmt,
            openId: ropenides.data

          };
          // list.push(fund);


          console.log(list);
          var jsonArr = JSON.stringify(fund);
          console.log(jsonArr);
          // var context = app.context;
          await context.init()
          const perseResult = context.callContainer({
            path: '/alipaycloud/baidu/calFundDetl',
            method: 'POST',
            data: jsonArr,
            header: {
              "X-Alipay-Service": "yongserver", //换成你自己的环境内的服务名
              "Content-Type": "application/json" // 不加这一行，其实就不需要服务端返回的数据限制为json了。啥都不加，其实默认就是 text，如果加了 json，jsapi就可以帮助反序列化json，
            }
          }).then((res) => {
            console.log("perseOcrDetl add then respose", res.data.data[0]);

            c1.callFunction({
              name: "addFundInfo",
              data: {
                action: "addFundInfo",
                fundName: res.data.data[0].fundName,
                fundAmt: res.data.data[0].fundAmt,
                fundCode: res.data.data[0].fundCode,
                importDate: res.data.data[0].fixDate,
                fundCount: res.data.data[0].fundCount,
                todayAmt: res.data.data[0].todayAmt,
                openId: ropenides.data



              }
            });


          })


          // c1.callFunction({
          //   name: "addFundInfo",
          //   data: {
          //     action: "addFundInfo",
          //     fundName: fundName,
          //     fundAmt: fundAmt,
          //     fundCode: fundCode,
          //     importDate: yesterday

          //   }
          // });
        }


      }
    };







    var endDate = new Date();

    // 使用getTime()方法获取时间戳（毫秒）  
    var endDateTime = endDate.getTime();

    // 打印时间戳  
    console.log(endDateTime);
    my.reLaunch({
      url: "../index/index" // url详解请见【路由使用须知】
    });


  },
  async callBase64Ocr(e) {
    console.log("callBase64Ocr:", e);

    let ropenides = my.getStorageSync({
      key: 'openid'
    });

    console.log("eeeee", ropenides.data);
    var context = app.context;
    await context.init()
    const res = context.callContainer({
      path: '/alipaycloud/baidu/baseocr',
      method: 'POST',
      data: {
        "openId": ropenides.data,
        "base64Str": e
      },
      header: {
        "X-Alipay-Service": "yongserver", //换成你自己的环境内的服务名
        "Content-Type": "application/json" // 不加这一行，其实就不需要服务端返回的数据限制为json了。啥都不加，其实默认就是 text，如果加了 json，jsapi就可以帮助反序列化json，
      }
    }).then((res) => {
      console.log("add then respose", res);
      let rees = my.setStorageSync({
        key: 'fundInfoList',
        data: res.resultData.data
      });

      my.reLaunch({
        url: "../index/index?data=" + res.resultData.data // url详解请见【路由使用须知】
      });
      console.log(rees);
      if (rees.success) {
        console.log("执行成功");

      }


    })


  },
  onItemClick(ev) {
    this.getLogin(this.data.navs[ev.currentTarget.dataset.index].link)
  },
});